import 'package:aero_frisbee/app/state/af_app_state_ext.dart';
import 'package:aero_frisbee/app/state/app_cache_state.dart';
import 'package:aero_frisbee/core/extension/string_ext.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:aero_frisbee/pages/modues/message/pages/followed/view_model/af_followed_list_view_model.dart';
import 'package:aero_frisbee/pages/modues/post/af_profile_detail_screen/views/af_more_action_sheet.dart';
import 'package:aero_frisbee/pages/modues/post/af_profile_detail_screen/views/af_report_options_sheet.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

import 'views/af_message_cell.dart';
import 'views/input/af_bottom_input_field_view.dart';
import 'views/input/af_chat_textfield.dart';
import 'viwe_model/af_bottom_input_field_view_model.dart';
import 'viwe_model/af_message_detail_view_model.dart';

final inputTextProvider = StateProvider.autoDispose<String>((ref) {
  return '';
});

class AfMessageDetailScreen extends ConsumerStatefulWidget {
  const AfMessageDetailScreen({super.key, required this.userId});
  final String userId;
  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _AfMessageDetailScreenState();
}

class _AfMessageDetailScreenState extends ConsumerState<AfMessageDetailScreen> {
  final TextEditingController _textController = TextEditingController();
  final FocusNode _focusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    ref.listen(afBottomInputTypeServiceProvider, (previousData, newData) {
      final isShouldHiddenKeyboard = newData.maybeWhen(
        orElse: () => true,
        input: () => false,
      );
      if (isShouldHiddenKeyboard) {
        unfocus();
      } else {
        focus();
      }
    });
    final curLoginUser = ref.watch(curlUserInfoProvider);
    final userServiceAccountId = curLoginUser?.userServiceAccountId;
    final userInfo =
        ref.watch(getUserInfoFutureProvider(userId: widget.userId)).maybeWhen(
              orElse: () => null,
              data: (data) => data,
            );

    ref.listen(unfriendServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        ref.invalidate(getUserInfoFutureProvider);
      }
    });
    ref.listen(unblockServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        ref.invalidate(getBlockListFutureProvider);
        ref.invalidate(getUserInfoFutureProvider);
        Navigator.popUntil(context, (route) => route.isFirst);
      }
    });

    ref.listen(reportServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        "Report Success".toast();
      }
    });
    return Stack(
      children: [
        Scaffold(
          backgroundColor: const Color(0xffF6F7F8),
          appBar: AppBar(
            backgroundColor: Colors.white,
            leading: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                Navigator.of(context).maybePop();
              },
              child: Align(
                alignment: Alignment.centerLeft,
                child: Padding(
                  padding: const EdgeInsets.only(
                    left: 20,
                  ),
                  child: Assets.icons.iconMineBack.image(width: 25),
                ),
              ),
            ),
            title: Text(
              userInfo?.nickname ?? '',
              style: const TextStyle(
                color: Color(0xff404040),
                fontWeight: FontWeight.normal,
                fontSize: 16,
              ),
              textAlign: TextAlign.center,
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            ),
            actions: [
              if (userServiceAccountId != widget.userId)
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    showAfMoreActionSheet(
                      context,
                      isFriend: userInfo?.isFriend == true,
                      isBlock: userInfo?.isBlock == true,
                      onFollowClick: () {
                        if (userInfo?.isFriend == true) {
                          ref
                              .read(unfriendServiceProvider.notifier)
                              .unfriend(userId: userInfo?.userId ?? '');
                        } else {
                          ref
                              .read(addFriendServiceProvider.notifier)
                              .addFriend(userId: userInfo?.userId ?? '');
                        }
                      },
                      onBlackClick: () {
                        if (userInfo?.isBlock == true) {
                          ref
                              .read(unblockServiceProvider.notifier)
                              .unblock(broadcasterId: userInfo?.userId ?? '');
                        } else {
                          ref
                              .read(blockServiceProvider.notifier)
                              .block(broadcasterId: userInfo?.userId ?? '');
                        }
                      },
                      onReportClick: () {
                        showAfReportOptionsSheet(
                          context,
                          onReportClick: (report) {
                            ref.read(reportServiceProvider.notifier).report(
                                complainSub: report,
                                userId: userInfo?.userId ?? '');
                          },
                        );
                      },
                    );
                  },
                  child: Padding(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 20, vertical: 6),
                    child: Assets.icons.iconLightMore.image(width: 28),
                  ),
                )
            ],
          ),
          body: SafeArea(
            child: ref
                .watch(
                    afMessageDetailListServiceProvider(userId: widget.userId))
                .maybeWhen(
                  orElse: () => Container(),
                  loading: () =>
                      const Center(child: CircularProgressIndicator()),
                  data: (data) => _buildBody(data),
                ),
          ),
        ),
      ],
    );
  }

  focus() {
    _focusNode.requestFocus();
  }

  unfocus() {
    _focusNode.unfocus();
  }

  _buildBody(List<RCIMIWMessage> data) {
    final inputTextState = ref.watch(inputTextProvider);

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: Column(
        children: [
          Expanded(
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onPanDown: (_) {
                ref.read(afBottomInputTypeServiceProvider.notifier).exitEdit();
                FocusScope.of(context).requestFocus(FocusNode());
              },
              child: ListView.separated(
                reverse: true,
                padding: const EdgeInsets.only(top: 20),
                itemBuilder: (context, index) {
                  return AfMessageCell(
                    message: data[index],
                  );
                },
                separatorBuilder: (context, index) => const SizedBox(
                  height: 10,
                ),
                itemCount: data.length,
              ),
            ),
          ),
          AfBottomInputFieldView(
            userId: widget.userId,
            sendOnClick: () {
              // 在这里处理发送逻辑
              if (_textController.text.isNotEmpty) {
                ref
                    .read(afMessageDetailListServiceProvider(
                            userId: widget.userId)
                        .notifier)
                    .sendTextMessage(_textController.text);
                ref.read(inputTextProvider.notifier).state = '';

                _textController.clear();
              }
            },
            inputText: inputTextState,
            textController: _textController,
            inputField: AfChatTextfield(
              focusNode: _focusNode,

              // 设置回车键点击事件
              onEditingComplete: () {
                // 在这里处理搜索逻辑
                if (_textController.text.isNotEmpty) {
                  // final conversation = ref.read(curConversationProvider);
                  // // ref
                  // //     .read(sendMessageOperatorServiceProvider(
                  // //             conversation: conversation)
                  // //         .notifier)
                  // //     .sendText(_textController.text);

                  ref
                      .read(afMessageDetailListServiceProvider(
                              userId: widget.userId)
                          .notifier)
                      .sendTextMessage(_textController.text);
                  ref.read(inputTextProvider.notifier).state = '';

                  _textController.clear();
                }
              },
              onChange: (value) {
                ref.read(inputTextProvider.notifier).state = value;
              },
              onTap: () {
                ref.read(afBottomInputTypeServiceProvider.notifier).editIn();
              },
              borderRadius: 4,
              controller: _textController,
              fillColor: const Color(0xffFFFFFF),
              placeholder: 'Enter here......',
            ),
          )
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(AfMessageDetailScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
